<?php
/**
 * StatZone default Player controller
 * 
 * @package    USS.StatZone
 * @subpackage Components
 * @link www.ugenix.co.za www.statzone.co.za
 * @license		Commercial
 * @author Salie Hendricks
 */
 
 //
 //TODO: Copied this from Player controller...
 // needs to be coded correctly
 //

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.controller' );

/**
 * @package		USS
 * @subpackage	StatZone
 */
class StatZoneControllerScorecard extends JController
{
	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct()
	{
		parent::__construct();

        // Register Extra tasks
		$this->registerTask( 'add'  , 	'edit' );
        $this->registerTask( 'apply',		'save' );
        $this->registerTask( 'unpublish',	'publish' );
	}

    /**
	 * Display the list of teams
	 */
	function display()
	{
		global $mainframe;

		$db =& JFactory::getDBO();

		$context			= 'com_statzone.scorecard.list.';
		$filter_order		= $mainframe->getUserStateFromRequest( $context.'filter_order',		'filter_order',		'scorecard.firstinndate',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $context.'filter_order_Dir',	'filter_order_Dir',	' ',			'word' );
		$filter_provid		= $mainframe->getUserStateFromRequest( $context.'filter_provid',		'filter_provid',		'',			'int' );
        $filter_hometeamid		= $mainframe->getUserStateFromRequest( $context.'filter_hometeamid',		'filter_hometeamid',		'',			'int' );
        $filter_awayteamid		= $mainframe->getUserStateFromRequest( $context.'filter_awayteamid',		'filter_awayteamid',		'',			'int' );
		$search				= $mainframe->getUserStateFromRequest( $context.'search',			'search',			'',			'string' );

		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( $context.'limitstart', 'limitstart', 0, 'int' );

		$where = array();
        
		if ($filter_provid) {
			$where[] = ' hometeam.provinceid = ' . (int) $filter_provid;
		}
        if ($filter_hometeamid) {
			$where[] = ' scorecard.teamidhome = ' . (int) $filter_hometeamid;
		}
        if ($filter_awayteamid) {
			$where[] = ' scorecard.teamidopponent = ' . (int) $filter_awayteamid;
		}
        
		if ($search) {
			$where[] = ' LOWER(hometeam.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false ) . ' OR '
                       .' LOWER(awayteam.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false ). ' OR '
                       .' LOWER(scorecard.season) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
		}

		$where		= count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '';
		$orderby	= ' ORDER BY '. $filter_order .'  '. $filter_order_Dir ;

		// get the total number of records
		$query = 'SELECT COUNT(*)'
		. ' FROM #__statzone_scorecards AS scorecard'
        . ' INNER JOIN #__statzone_teams AS hometeam ON hometeam.id = scorecard.teamidhome'
        . ' INNER JOIN #__statzone_teams AS awayteam ON awayteam.id = scorecard.teamidopponent'
		. $where
		;
        
		$db->setQuery( $query );
		$total = $db->loadResult();

		jimport('joomla.html.pagination');
		$pageNav = new JPagination( $total, $limitstart, $limit );

		$query = 'SELECT scorecard.id as id, scorecard.teamidhome as hometeamid, scorecard.teamidopponent as opponentteamid, hometeam.name as hometeamname, awayteam.name as awayteamname,'.
                        'scorecard.firstinndate as firstinndate, scorecard.secondinndate as secondinndate, scorecard.innings as inn, scorecard.result as result, scorecard.resultdetails, scorecard.published'
                . ' FROM #__statzone_scorecards AS scorecard'
                . ' INNER JOIN #__statzone_teams AS hometeam ON hometeam.id = scorecard.teamidhome'
                . ' INNER JOIN #__statzone_teams AS awayteam ON awayteam.id = scorecard.teamidopponent'
		. $where
		. $orderby
        ;
       	$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
       	$rows = $db->loadObjectList();
        //echo $query;
		$javascript		= 'onchange="document.adminForm.submit();"';
		
        // ________build list of provinces ________
        $sql = 'SELECT id as provinceid, name'
		. ' FROM #__statzone_province'
		;
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_statzone' );
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}

		$provincelist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Province -' ), 'provinceid', 'name' );
		$provincelist			= array_merge( $provincelist, $db->loadObjectList() );
		$lists['provinceid']		= JHTML::_('select.genericlist',   $provincelist, 'provinceid', 'class="inputbox" size="1" ' .$javascript ,'provinceid', 'name', $row->provinceid );

        // ________build list of home teams________
        $sql = 'SELECT t.id as teamid, t.name AS teamname'
		. ' FROM #__statzone_teams AS t'
		. ' INNER JOIN #__statzone_clubs AS c ON c.id = t.clubid'
		. ' INNER JOIN #__statzone_province AS provinces ON c.provinceid = provinces.id'
        ;
		        
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_statzone' );
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}
		$hometeamlist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Team -' ), 'teamid', 'teamname' );
		$hometeamlist			= array_merge( $hometeamlist, $db->loadObjectList() );
		$lists['hometeamid']		= JHTML::_('select.genericlist',   $hometeamlist, 'teamid', 'class="inputbox" size="1"' .$javascript,'teamid', 'teamname', $row->teamidhome );

        $awayteamlist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Opponent Team -' ), 'teamid', 'teamname' );
		$awayteamlist			= array_merge( $awayteamlist, $db->loadObjectList() );
		$lists['opponentteamid']		= JHTML::_('select.genericlist',   $awayteamlist, 'teamid', 'class="inputbox" size="1"' .$javascript,'teamid', 'teamname', $row->teamidopponent );
        
        $resultlist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Result -' ), 'id', 'result' );
		//$resultlist			= array_merge( $resultlist, $db->loadObjectList() );
		$lists['resultlist']		= JHTML::_('select.genericlist',   $resultlist, 'resultlist', 'class="inputbox" size="1"' .$javascript,'id', 'result', '' );

        // table ordering
		$lists['order_Dir']	= $filter_order_Dir;
		$lists['order']		= $filter_order;

		// search filter
		$lists['search']= $search;

        // add mootools
        /*JHTML::_('behavior.mootools');
        $js = "<script>window.addEvent('domready', function()
        {
            $('adminForm').addEvent('submit', function(e)
            {
                // Stop the form from submitting
                new Event(e).stop();
                // Update the page
                this.send({ update: $('update') });
            });
        });</script>";
        //echo $js;*/
		require_once(JPATH_COMPONENT.DS.'views'.DS.'scorecards.php');
		StatZoneViewScorecards::scorecards( $rows, $pageNav, $lists );
	}
    
	/**
	 * display the edit form
	 * @return void
	 */
	function edit()
	{
        $db		=& JFactory::getDBO();
		$user	=& JFactory::getUser();
        $post	= JRequest::get( 'post' );
        
        if ($this->_task == 'edit') 
        {
			$cid	= JRequest::getVar('cid', array(0), 'method', 'array');
			$cid	= array((int) $cid[0]);
		} 
        else 
        {
			$cid	= array( 0 );
		}

        $lists = array();
        
		$option = JRequest::getCmd('option');     
        
        $row =& JTable::getInstance('scorecards', 'Table');
		$row->load( $cid[0] );


        /*// ________build list of clubs________
        $sql = 'SELECT c.id as clubid, content.title AS name'
		. ' FROM #__statzone_clubs AS c'
		. ' INNER JOIN #__content AS content ON c.contentid = content.id'
		. ' INNER JOIN #__statzone_province AS provinces ON c.provinceid = provinces.id'
        ;
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_statzone' );
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}

		$clublist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Club -' ), 'clubid', 'name' );
		$clublist			= array_merge( $clublist, $db->loadObjectList() );
		$lists['homeclubid']		= JHTML::_('select.genericlist',   $clublist, 'clubid', 'class="inputbox" size="1"','clubid', 'name', $row->clubid );
        */
        // ________build list of teams________
        
        $sql = 'SELECT t.id as teamid, t.name AS teamname'
		. ' FROM #__statzone_teams AS t'
		. ' INNER JOIN #__statzone_clubs AS c ON c.id = t.clubid'
		. ' INNER JOIN #__statzone_province AS provinces ON c.provinceid = provinces.id'
        . ' ORDER BY  t.name'
		; //TODO include a where province dropdown was selected
        
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_statzone' );
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}
        $hometeamid = $post['hometeamidvalue'];//$post['hometeamid'];
        
        $javascript		= ' onchange="buildresultlist();" '; //; document.adminForm.task.value=\'buildscorecardrows\' ;document.adminForm.submit();
        $hometeamlistenabled = $row->id > 0 ? ' disabled = "true" ' : ''; //if its new enable the dropdown else disable it for existing scorecard edits
        $hometeamlist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Home Team-' ), 'teamid', 'teamname' );
		$hometeamlist			= array_merge( $hometeamlist, $db->loadObjectList() );
		$lists['hometeamid']		= JHTML::_('select.genericlist',   $hometeamlist, 'hometeamid', 'class="inputbox" size="1" '.$hometeamlistenabled . $javascript,'teamid', 'teamname', $row->teamidhome );

        $awayteamlist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Opponent Team-' ), 'teamid', 'teamname' );
		$awayteamlist			= array_merge( $awayteamlist, $db->loadObjectList() );
		$lists['oppteamid']		= JHTML::_('select.genericlist',   $awayteamlist, 'oppteamid', 'class="inputbox" size="1"' ,'teamid', 'teamname', $row->teamidopponent );
        
        $lists['published'] 		= JHTML::_('select.booleanlist',  'published', 'class="inputbox"', $row->published );
        
        //find the home team id and name
        if($row->id>0) //viewing an existing
        {
            $sql = 'SELECT t.id as teamid, t.name AS teamname'
            . ' FROM #__statzone_teams AS t'
            . ' INNER JOIN #__statzone_clubs AS c ON c.id = t.clubid'
            . ' INNER JOIN #__statzone_province AS provinces ON c.provinceid = provinces.id'
            . ' WHERE t.id = ' . $row->teamidhome//$row->winningteamid
            ;
            $db->setQuery($sql);
            if (!$db->query())
            {
                $this->setRedirect( 'index.php?option=com_statzone&c=scorecard' );
                return JError::raiseWarning( 500, $db->getErrorMsg() );
            }
            $hometeamdetails = $db->loadRow();
            
            $resultlist[]		= JHTML::_('select.option',  '1', JText::_( $hometeamdetails[1] . ' team win' ), 'teamid', 'teamname');
            $resultlist[]		= JHTML::_('select.option',  '2', JText::_( $hometeamdetails[1] . ' team loose' ), 'teamid', 'teamname');
            $resultlist[]		= JHTML::_('select.option',  '-3', JText::_( 'Draw' ), 'teamid', 'teamname');
            $resultlist[]		= JHTML::_('select.option',  '-4', JText::_( 'Match abandoned' ), 'teamid', 'teamname');
            
            //$rSelIndx = ($row->winningteamid > 0 & $row->winningteamid == $row->teamidhome) ? 1 : 2;
            if($row->winningteamid == $row->teamidhome)
            {
                //home team won
                $rSelIndx = 1;
            }
            else if($row->winningteamid > 0 & $row->winningteamid != $row->teamidhome)
            {
                $rSelIndx = 2;
            }
            else
            {
                $rSelIndx = $row->winningteamid;
            }
            
            $lists['resultlist']		= JHTML::_('select.genericlist',   $resultlist, 'resultlist', 'class="inputbox" size="1" ' ,'teamid', 'teamname', $rSelIndx );
            
            //update the resultdetails...if it endswith wickets or runs
            //if($row->resultdetails > '')
            //{
            //    $row->resultdetails = strstr($row->resultdetails,'wickets') ? trim(str_replace('wickets','',$row->resultdetails)) : trim(str_replace('runs','',$row->resultdetails));
            //}
        }
        
        //$lists['captureteam'] 		= JHTML::_('select.booleanlist',  'captureteam', 'class="inputbox"', $row->published );
        
        
        $innings1row = '';
        $statstable = '';
        
        $row =& JTable::getInstance('scorecards', 'Table');
		$row->load( $cid[0] );
        
        if($row->id > 0) //this is an existing scorecard, start with a list of players from the players for the scorecard
        {
            //get the list of players for the scorecard
            $sql = 'SELECT DISTINCT player.id AS playerid, player.firstname AS firstname, player.surname AS surname '
            . 'FROM #__statzone_scorecards as scorecard '
            . 'LEFT JOIN #__statzone_battingscores as bat ON bat.scorecardid = scorecard.id '
            . 'LEFT JOIN #__statzone_players as player ON player.id = bat.playerid '
            . 'WHERE scorecard.id = ' . $row->id
            . ' UNION '
            . 'SELECT DISTINCT player.id AS playerid, player.firstname AS firstname, player.surname AS surname '
            . 'FROM #__statzone_scorecards as scorecard '
            . 'LEFT JOIN #__statzone_bowlingscores as bowl ON bowl.scorecardid = scorecard.id '
            . 'LEFT JOIN #__statzone_players as player ON player.id = bowl.playerid '
            . 'WHERE scorecard.id = ' . $row->id
            . ' ORDER BY surname'
            ;
            //echo $sql;
            $db->setQuery($sql);
            if (!$db->query())
            {
                $this->setRedirect( 'index.php?option=com_statzone' );
                return JError::raiseWarning( 500, $db->getErrorMsg() );
            }
            $playerlist = $db->loadObjectList() ;
            $playeridsstatsmain = ''; //a string to concat the player ids used later
            
            //foreach of these players create a row, 
            foreach($playerlist as $playerrow) //fetch the batting and bowling stats
            {
                $playerid = $playerrow->playerid;
                if($playerid > 0 )
                {
                    $playeridsstatsmain = $playeridsstatsmain . $playerid . ',';
                    $sql = 'SELECT DISTINCT bat1.runs, bat2.runs, bat1.notout, bat2.notout, '
                    . ' bowl1.overs , bowl1.maidens , bowl1.runs, bowl1.wickets, '
                    . ' bowl2.overs , bowl2.maidens , bowl2.runs, bowl2.wickets, ' 
                    . ' bat1.id as bat1id, bat2.id as bat2id, bowl1.id as bowl1id, bowl2.id as bowl2id '
                    . ' FROM #__statzone_scorecards as scorecard '
                    . ' LEFT JOIN #__statzone_battingscores as bat1 ON bat1.scorecardid = scorecard.id AND bat1.inningsno = 1 AND bat1.playerid =' . $playerid
                    . ' LEFT JOIN #__statzone_bowlingscores as bowl1 ON bowl1.scorecardid = scorecard.id AND bowl1.inningsno = 1 AND bowl1.playerid =' . $playerid
                    . ' LEFT JOIN #__statzone_battingscores as bat2 ON bat2.scorecardid = scorecard.id AND bat2.inningsno = 2 AND bat2.playerid =' . $playerid
                    . ' LEFT JOIN #__statzone_bowlingscores as bowl2 ON bowl2.scorecardid = scorecard.id AND bowl2.inningsno = 2 AND bowl2.playerid =' . $playerid
                    . ' WHERE scorecard.id = ' . $row->id
                    //. ' AND bat1.playerid =' . $playerid
                    //. ' AND bowl1.playerid =' . $playerid
                    //. ' AND bat2.playerid =' . $playerid
                    //. ' AND bowl2.playerid =' . $playerid
                    ;
                    
                    $db->setQuery($sql);
                    if (!$db->query())
                    {
                        $this->setRedirect( 'index.php?option=com_statzone' );
                        return JError::raiseWarning( 500, $db->getErrorMsg() );
                    }
                    $playerstats = $db->loadRow() ;
                    
                    $playername = $playerrow->surname .', '.$playerrow->firstname;
                    //echo '<br>SCid='.$row->id.' $playername:' . $playername . ' 1st inn run= ' . $playerstats[0];
                    //get the rest of the stats
                    
                    $inn1NotOut = $playerstats[2] ==1 ? '*' : '';
                    $inn2NotOut = $playerstats[3] ==1 ? '*' : '';
                    //if this is an existing scorecard then show the results
                    //else just show empty values
                    $innings1row = $innings1row . ''
                        .'<tr>'
                        .'<td nowrap=\'true\'>'.$playername .' ['.$playerid.']</td>'
                        .'<td><input class="inputbox" type="text" name="firstinn_runsbatting_'.$playerid.'" id="firstinn_runsbatting_'.$playerid.'" size="10" value="'.$playerstats[0]. $inn1NotOut .'" /><input type="hidden" name="bat1id_'.$playerid.'" id="bat1id_'.$playerid.'" value="'.$playerstats[12].'" /></td>'
                        .'<td><input class="inputbox" type="text" name="secondinn_runsbatting_'.$playerid.'" id="secondinn_runsbatting_'.$playerid.'" size="10" value="'. $playerstats[1]. $inn2NotOut . '" /><input type="hidden" name="bat2id_'.$playerid.'" id="bat2id_'.$playerid.'" value="'.$playerstats[13].'" /></td>'
                        .'<td><input class="inputbox" type="text" name="firstinn_O_'.$playerid.'" id="firstinn_O_'.$playerid.'" size="10" value="'.$playerstats[4].'" /></td>'
                        .'<td><input class="inputbox" type="text" name="firstinn_M_'.$playerid.'" id="firstinn_M_'.$playerid.'" size="10" value="'.$playerstats[5].'" /></td>'
                        .'<td><input class="inputbox" type="text" name="firstinn_R_'.$playerid.'" id="firstinn_R_'.$playerid.'" size="10" value="'.$playerstats[6].'" /></td>'
                        .'<td><input class="inputbox" type="text" name="firstinn_W_'.$playerid.'" id="firstinn_W_'.$playerid.'" size="10" value="'.$playerstats[7].'" /><input type="hidden" name="bowl1id_'.$playerid.'" id="bowl1id_'.$playerid.'" value="'.$playerstats[14].'" /></td>'
                        .'<td><input class="inputbox" type="text" name="secondinn_O_'.$playerid.'" id="secondinn_O_'.$playerid.'" size="10" value="'.$playerstats[8].'" /></td>'
                        .'<td><input class="inputbox" type="text" name="secondinn_M_'.$playerid.'" id="secondinn_M_'.$playerid.'" size="10" value="'.$playerstats[9].'" /></td>'
                        .'<td><input class="inputbox" type="text" name="secondinn_R_'.$playerid.'" id="secondinn_R_'.$playerid.'" size="10" value="'.$playerstats[10].'" /></td>'
                        .'<td><input class="inputbox" type="text" name="secondinn_W_'.$playerid.'" id="secondinn_W_'.$playerid.'" size="10" value="'.$playerstats[11].'" /><input type="hidden" name="bowl2id_'.$playerid.'" id="bowl2id_'.$playerid.'" value="'.$playerstats[15].'" /></td>'
                        .'</tr>';
                }
                
            }//ends for
            
            if($innings1row  > '') //might be an empty stats sheet
            {
                $statstable = StatZoneControllerScorecard::getStatzTable($innings1row);
            }
            
            //get a list of players that are part of the hometeam that are not part of the playerlist captured
            //put them in a div for access later 35,58,2,
            $playeridsstatsmain = substr($playeridsstatsmain,0,strlen($playeridsstatsmain) - 1);
            
            if(strlen($playeridsstatsmain) > '')
            {
                //get the list of players that are not in the statz sheet already and 
                $sql = 'SELECT DISTINCT player.id AS playerid, player.firstname AS firstname, player.surname AS surname '
                . ' FROM #__statzone_players as player'
                . ' INNER JOIN #__statzone_playerteams as pt ON player.id = pt.playerid '
                . ' WHERE pt.teamid = ' . $row->teamidhome
                . ' AND player.id NOT IN ('.$playeridsstatsmain.')'
                . ' ORDER BY player.surname'
                ;
             
            }
            else
            {
                //get the list of players that are not in the statz sheet already -- this case there are no players in the stats sheet
                $sql = 'SELECT DISTINCT player.id AS playerid, player.firstname AS firstname, player.surname AS surname '
                . ' FROM #__statzone_players as player'
                . ' INNER JOIN #__statzone_playerteams as pt ON player.id = pt.playerid '
                . ' WHERE pt.teamid = ' . $row->teamidhome
                . ' ORDER BY player.surname'
                ;
            }
            $db->setQuery($sql);
            if (!$db->query())
            {
                $this->setRedirect( 'index.php?option=com_statzone' );
                return JError::raiseWarning( 500, $db->getErrorMsg() );
            }
            $playerlist = $db->loadObjectList() ;
            
            $innings1row = '';
            $otherplayerstatsrows = '';
            foreach($playerlist as $playerrow) //fetch the batting and bowling stats
            {
                $playerid = $playerrow->playerid;
                $playername = $playerrow->surname .', '.$playerrow->firstname;
                $innings1row = $innings1row . ''
                    .'<tr>'
                    .'<td nowrap=\'true\'>'.$playername .' ['.$playerid.']</td>'
                    .'<td><input class="inputbox" type="text" name="firstinn_runsbatting_'.$playerid.'" id="firstinn_runsbatting_'.$playerid.'" size="10" value="" /><input type="hidden" name="bat1id_'.$playerid.'" id="bat1id_'.$playerid.'" value="" /></td>'
                    .'<td><input class="inputbox" type="text" name="secondinn_runsbatting_'.$playerid.'" id="secondinn_runsbatting_'.$playerid.'" size="10" value="" /><input type="hidden" name="bat2id_'.$playerid.'" id="bat2id_'.$playerid.'" value="" /></td>'
                    .'<td><input class="inputbox" type="text" name="firstinn_O_'.$playerid.'" id="firstinn_O_'.$playerid.'" size="10" value="" /></td>'
                    .'<td><input class="inputbox" type="text" name="firstinn_M_'.$playerid.'" id="firstinn_M_'.$playerid.'" size="10" value="" /></td>'
                    .'<td><input class="inputbox" type="text" name="firstinn_R_'.$playerid.'" id="firstinn_R_'.$playerid.'" size="10" value="" /></td>'
                    .'<td><input class="inputbox" type="text" name="firstinn_W_'.$playerid.'" id="firstinn_W_'.$playerid.'" size="10" value="" /><input type="hidden" name="bowl1id_'.$playerid.'" id="bowl1id_'.$playerid.'" value="" /></td>'
                    .'<td><input class="inputbox" type="text" name="secondinn_O_'.$playerid.'" id="secondinn_O_'.$playerid.'" size="10" value="" /></td>'
                    .'<td><input class="inputbox" type="text" name="secondinn_M_'.$playerid.'" id="secondinn_M_'.$playerid.'" size="10" value="" /></td>'
                    .'<td><input class="inputbox" type="text" name="secondinn_R_'.$playerid.'" id="secondinn_R_'.$playerid.'" size="10" value="" /></td>'
                    .'<td><input class="inputbox" type="text" name="secondinn_W_'.$playerid.'" id="secondinn_W_'.$playerid.'" size="10" value="" /><input type="hidden" name="bowl2id_'.$playerid.'" id="bowl2id_'.$playerid.'" value="" /></td>'
                    .'</tr>';
            }
            
            $addplayerstatstable = StatZoneControllerScorecard::getStatzTable($innings1row);
            
            //create the nice slide to hide the other players
            if($innings1row > '')
            {
                $otherplayerstatscontent = '{slide=Add more players}'.$addplayerstatstable.'{/slide}';
                $otherplayerstatscontent = StatZoneControllerScorecard::createslidecontent($otherplayerstatscontent);
            }
            $statstable = $statstable . $otherplayerstatscontent;
            
        }
        
         //Current season:
        $currentSeason = '';
        $currentDateMonth = date('m');
        $currentDateYear = date('Y');
        if($currentDateMonth < 7) //before july
        {
            $currentSeason = ($currentDateYear - 1) . '/' . $currentDateYear ; //2007/2008
        }
        else
        {
            $currentSeason = $currentDateYear . '/' . ($currentDateYear + 1); //2008/2009
        }
        $row->currentseason = $currentSeason;
        
        
        require_once(JPATH_COMPONENT.DS.'views'.DS.'scorecards.php');
        StatZoneViewScorecards::singleScorecard( $row, $lists ,$statstable);
    }

    function getStatzTable(&$statzrows)
    {
        $statstable = '
                <table class="adminlist">
                    <thead>
                    <tr>
                        <th width="20" colspan="1">
                            
                        </th>
                        <th width="10" colspan="2">
                            Batting
                        </th>
                        <th width="10" colspan="8">
                            Bowling
                        </th>
                    </tr>
                    <tr>
                        <th width="20" colspan="1">
                            
                        </th>
                        <th width="10" colspan="1">
                            1st
                        </th>
                        <th width="10" colspan="1">
                            2nd
                        </th>
                        <th width="10" colspan="4">
                            1st
                        </th>
                        <th width="10" colspan="4">
                            2nd
                        </th>
                    </tr>
                    <tr>
                        <th width="10">
                            Players
                        </th>
                        <th width="10">
                            Runs
                        </th>
                         <th width="10">
                           Runs
                        </th>
                        
                        <th width="10">
                           O
                        </th>
                        <th width="10">
                           M
                        </th>
                        <th width="10">
                            R
                        </th>
                        <th width="10">
                            W
                        </th>
                        
                        <th width="10">
                            O
                        </th>
                        <th width="10">
                            M
                        </th>
                        <th width="10">
                            R
                        </th>
                        <th width="10">
                            W
                        </th>
                    </tr>
                    </thead>
                    <tbody>
                        '.$statzrows.'
                    </tbody>
                </table><br>';
        
        return $statstable;
                
    }
    /**
	 * create a slider for the rest of the player that belong to that team.Uses the jwts code (JoomlaWorks tab/slider)
	 * @return string with slider code and content
	 */
    function createslidecontent(&$content)
    {
        // just startup
		global $mainframe, $loadJWTSscripts;
        
		// checking
		if ( !preg_match("#{slide=.+?}#s", $content) ) {
			return $content;
		}

		// JS loader selection
		$use_optimized_loader = 0; // Use optimized JS code loader? 0=no and 1=yes. Default is 0.

		//$plugin =& JPluginHelper::getPlugin('content', 'jwts');
		//$pluginParams = new JParameter( $plugin->params );

		// j!1.5 paths
		$mosConfig_absolute_path 	= JPATH_SITE;
		$mosConfig_live_site 		= $mainframe->isAdmin() ? $mainframe->getSiteURL() : JURI::base();
		if(substr($mosConfig_live_site, -1)=="/") $mosConfig_live_site = substr($mosConfig_live_site, 0, -1);

		// Parameters
		$enable_slides 		= 1;//$pluginParams->get('enable_slides', 1);
		$slides_slidespeed 	= 50;//$pluginParams->get('slides_slidespeed', '30');
		$slides_timer 		= 10;//$pluginParams->get('slides_timer', '10');

		if(!$loadJWTSscripts) {
			$loadJWTSscripts=1;
			$header = "<!-- JoomlaWorks \"Tabs & Slides\" Plugin (v2.3) starts here -->
						<style type=\"text/css\" media=\"screen\">
							@import \"$mosConfig_live_site/plugins/content/plugin_jw_ts/tabs_slides.css\";
						</style>
						<style type=\"text/css\" media=\"print\">.jwts_tabbernav{display:none;}</style>
						<script type=\"text/javascript\">var jwts_slideSpeed=".$slides_slidespeed."; var jwts_timer=".$slides_timer.";</script>
						<script type=\"text/javascript\" src=\"$mosConfig_live_site/plugins/content/plugin_jw_ts/tabs_slides_comp.js\"></script>
					  ";
			if($use_optimized_loader) {
				$header .= "<script type=\"text/javascript\" src=\"$mosConfig_live_site/plugins/content/plugin_jw_ts/tabs_slides_opt_loader.js\"></script>";
			} else {
				$header .= "<script type=\"text/javascript\" src=\"$mosConfig_live_site/plugins/content/plugin_jw_ts/tabs_slides_def_loader.js\"></script>";
			}
			$header .= "<!-- JoomlaWorks \"Tabs & Slides\" Plugin (v2.3) ends here -->";

			// cache check
			if($mainframe->getCfg('caching') && ($option=='com_frontpage' || $option=='')) {
				echo $header;
			} else {
				$mainframe->addCustomHeadTag($header);
			}
		}

        // Start Slides Replacement
		if($enable_slides) {        
			if(!$_REQUEST['print'] && $_REQUEST['format']!="pdf") {            
				if (preg_match_all("/{slide=.+?}/", $content, $matches, PREG_PATTERN_ORDER) > 0) {
					foreach ($matches[0] as $match) {
						$match = str_replace("{slide=", "", $match);
						$match = str_replace("}", "", $match);
						$content = str_replace( "{slide=".$match."}", "<div class=\"jwts_title\"><div class=\"jwts_title_left\"><a href=\"javascript:void(null);\" title=\"Click to open!\" class=\"jwts_title_text\">".$match."</a></div></div><div class=\"jwts_slidewrapper\"><div>", $content );
						$content = str_replace( "{/slide}", "</div></div>", $content );
					}
                    
				}
			} else {
            
				if (preg_match_all("/{slide=.+?}/", $content, $matches, PREG_PATTERN_ORDER) > 0) {
					foreach ($matches[0] as $match) {
						$match = str_replace("{slide=", "", $match);
						$match = str_replace("}", "", $match);
						$content = str_replace( "{slide=".$match."}", "<h3>&nbsp;".$match."</h3><div>", $content);
						$content= str_replace( "{/slide}", "</div>", $content);
					}
				}
			}
		}
        // End Slides Replacement
        
        return $content;
    }
    
	/**
	 * save a record (and redirect to main page)
	 * @return void
	 */
	function save()
	{
    
        // Check for request forgeries
		JRequest::checkToken() or die( 'Invalid Token' );

		// Initialize variables
		$db =& JFactory::getDBO();
        
		$post	= JRequest::get( 'post' );
		
        $row =& JTable::getInstance('scorecards', 'Table');

        //1. save the scorecard record and get the id
        //2. foreach player row where there is valid data - save the stats:
        //3.    save innings1 batting and bowling
        //4.    save innings2 batting and bowling
        
        $scorecardid= $post['id'];
        
        $season= $post['season'];
        $division= $post['division'];
        $hometeamid= $post['hometeamidvalue']; //$post['hometeamid'];
        $opponentteamid= $post['oppteamid'];
        
        $firstinndate= $post['firstinndate'];
        $secondinndate= $post['secondinndate'];
        $secondinndate = $secondinndate =='' ? 'null' : '\''.$secondinndate . '\'';
        
        $club_firstinnrunswickets = $post['club_firstinnrunswickets'];
        $club_secondinnrunswickets = $post['club_secondinnrunswickets'];
        $opp_firstinnrunswickets = $post['opp_firstinnrunswickets'];
        $opp_secondinnrunswickets = $post['opp_secondinnrunswickets'];
        $inningscount = $secondinndate == 'null' ? 1 : 2;
        
        $resultlist = $post['resultlist'];
        //$resultdetaillist = $post['resultdetaillist'] ? ' wickets' : ' runs';
        $resultdetails = trim($post['resultdetails']) ;
        
        $runsbatting= $post['runsbatting'];
        
        $published = $post['published'];
        
        //echo '$post["resultlist"] = ' . $post['resultlist'];
        $sql = 'SELECT t.id as teamid, t.name AS teamname'
        . ' FROM #__statzone_teams AS t'
        . ' INNER JOIN #__statzone_clubs AS c ON c.id = t.clubid'
        . ' INNER JOIN #__statzone_province AS provinces ON c.provinceid = provinces.id'
        . ' WHERE t.id = ' . $hometeamid
        ;
        $db->setQuery($sql);
        if (!$db->query())
        {
            $this->setRedirect( 'index.php?option=com_statzone&c=scorecard' );
            return JError::raiseWarning( 500, $db->getErrorMsg() );
        }
        
        $hometeamdetails = $db->loadRow();
        $winningteamid = -1;
        if($resultlist == 1)
        {
            $winningteamid = $hometeamid;
            $result = $hometeamdetails[1].  ' team win'; //get the text from the dropdown or fetch the name of the opponent and home team
        }
        else if ($resultlist == 2)
        {
            $winningteamid = $opponentteamid;
            $result = $hometeamdetails[1].  ' team loose';
        }
        else if ($resultlist == -3)//draw
        {
            $winningteamid = -3;
            $resultdetails = '';
            $result = 'Draw'; 
        }
        else if ($resultlist == -4)//abandoned
        {
            $winningteamid = -4;
            $resultdetails = '';
            $result = 'Match abandoned'; 
        }
        //$firstinn_runsbatting_test = $post["firstinn_runsbatting_3"];
        
        //echo '$firstinn_runsbatting_test = '. $firstinn_runsbatting_test;
        
        //TODO VALIDATE THAT THIS IS A UNIQUE SCORECARD - see spec for details
        $updating = $scorecardid > 0;
        if($updating) // its an update of an existing scorecard
        {
            $sql = 'UPDATE #__statzone_scorecards '
            . ' SET teamidopponent='. $opponentteamid . ','
            . ' season   =\''       . $season      . '\','
            . ' division =\''       . $division    . '\','
            . ' firstinndate =\''   . $firstinndate . '\','
            . ' secondinndate ='  . $secondinndate . ','
            . ' innings ='          . $inningscount . ','
            . ' result =\''         . $result . '\','
            . ' resultdetails =\''         . $resultdetails . '\','
            . ' winningteamid =\''         . $winningteamid . '\','
            . ' published =\''      . $published . '\','
            . ' firstinnscore_home =\''         . $club_firstinnrunswickets . '\','
            . ' secondinnscore_home =\''         . $club_secondinnrunswickets . '\','
            . ' firstinnscore_opponent =\''         . $opp_firstinnrunswickets . '\','
            . ' secondinnscore_opponent =\''         . $opp_secondinnrunswickets . '\''
            . ' WHERE id = '. $scorecardid ;
            
            //echo '<br>Heres the UPDATE SQL: ' . $sql;
            //return false;
            $db->setQuery($sql);
            if (!$db->query())
            {
                JError::raiseError( 500, $db->stderr() );
                return false;
            }
            
        }
        else // its a new scorecard with new stats
        {
            $sql = 'INSERT INTO #__statzone_scorecards ( teamidhome, teamidopponent, season, division, firstinndate, secondinndate, innings, result,resultdetails, winningteamid, published, firstinnscore_home, secondinnscore_home, firstinnscore_opponent, secondinnscore_opponent ) '
                    .                           'VALUES (' . $hometeamid . ',' . $opponentteamid. ',  \'' . $season. '\',\'' . $division . '\','
                    . '\'' . $firstinndate . '\','
                    . $secondinndate . ','
                    . '\'' . $inningscount. '\','
                    . '\'' . $result . '\','
                    . '\'' . $resultdetails . '\','
                    . '' . $winningteamid . ','
                    . '\'' . $published . '\','
                    . '\'' . $club_firstinnrunswickets . '\','
                    . '\'' . $club_secondinnrunswickets . '\','
                    . '\'' . $opp_firstinnrunswickets . '\','
                    . '\'' . $opp_secondinnrunswickets . '\''
                    . ')';
            //echo '<br><br> Heres the scorecard SQL: ' . $sql;
            
            /*A working script:
             INSERT INTO `jos_statzone_scorecards` ( teamidhome, teamidopponent, season, division, firstinndate, secondinndate, innings, result, winningteamid, published, firstinnscore_home, secondinnscore_home, firstinnscore_opponent, secondinnscore_opponent )
            VALUES ( 1, 2, '07/08', '1A', '2008-05-01', '2008-05-03', '2', 'result pending', 1, '1', '234', '', '234', '' ) */
            
            $db->setQuery($sql);
            if (!$db->query())
            {
                JError::raiseError( 500, $db->stderr() );
                return false;
            }
            $insertedId = $db->insertid();
            //echo "Inserted scorecard id:".$insertedId;
            
         }   
        //Now insert the stats!
        //For each player in the hometeam..
        //  look for the corresponding stats data 
        //  if it exists then 
        //      create a corresp insert statement and commit to the db
        //get the list of players for that team
        
        $sql = 'SELECT player.id as playerid, player.firstname, player.surname '
        . 'FROM #__statzone_players as player '
        . 'INNER JOIN #__statzone_playerteams as map ON map.playerid = player.id '
        . 'WHERE map.teamid = ' . $hometeamid
        . ' ORDER BY player.surName'
        ;
        $db->setQuery($sql);
        if (!$db->query())
        {
            $this->setRedirect( 'index.php?option=com_statzone' );
            return JError::raiseWarning( 500, $db->getErrorMsg() );
        }
        $playerlist = $db->loadObjectList() ;
        
        foreach($playerlist as $playerrow)
        {
            $playerid = $playerrow->playerid;
            
            //find if the corresp textboxes exist and contains data
            $firstinn_runsbatting = trim($post["firstinn_runsbatting_" . $playerid ]);
            $secondinn_runsbatting = trim($post["secondinn_runsbatting_" . $playerid ]);
            
            //check if the innings runs are out or notout - indicated with a * at the end
            $firstinn_notout = (substr($firstinn_runsbatting, -1, 1) == '*') > 0 ? 1 : 0 ; // if firstinn_runsbatting endswith * then its notout
            //echo '<br>$firstinn_notout = '. $firstinn_notout;
            if($firstinn_notout > 0)
            {
                $firstinn_runsbatting =  substr($firstinn_runsbatting,0,strlen($firstinn_runsbatting)-1);
            }
            
            $secondinn_notout = (substr($secondinn_runsbatting, -1, 1) == '*') > 0 ? 1 : 0 ;
            if($secondinn_notout)
            {
                $secondinn_runsbatting = substr($secondinn_runsbatting,0,strlen($secondinn_runsbatting)-1);
            }
            
            $firstinn_O = $post['firstinn_O_'. $playerid] >'' ? $post['firstinn_O_'. $playerid] : null;
            $firstinn_M = $post['firstinn_M_'. $playerid] >'' ? $post['firstinn_M_'. $playerid] : 0;
            $firstinn_R = $post['firstinn_R_'. $playerid] >'' ? $post['firstinn_R_'. $playerid] : 0;
            $firstinn_W = $post['firstinn_W_'. $playerid] >'' ? $post['firstinn_W_'. $playerid] : 0;;
            
            $secondinn_O = $post['secondinn_O_'. $playerid] >'' ? $post['secondinn_O_'. $playerid] : null;
            $secondinn_M = $post['secondinn_M_'. $playerid] >'' ? $post['secondinn_M_'. $playerid] : 0;
            $secondinn_R = $post['secondinn_R_'. $playerid] >'' ? $post['secondinn_R_'. $playerid] : 0;
            $secondinn_W = $post['secondinn_W_'. $playerid] >'' ? $post['secondinn_W_'. $playerid] : 0;
            
            $bat1id = $post['bat1id_'. $playerid];
            $bat2id = $post['bat2id_'. $playerid];
            $bowl1id = $post['bowl1id_'. $playerid];
            $bowl2id = $post['bowl2id_'. $playerid];
            
            $scorecardid =  $insertedId > 0 ? $insertedId : $scorecardid ; // use the inserted id if this is a new scorecard, else use the scorecard var
            // _____BATTING______
            //1st Innings
            if($bat1id > 0 & $firstinn_runsbatting == null)
            {
                //bat1id record exists in the existing scorecard but it has subsequently been removed
                $sql = 'DELETE FROM #__statzone_battingscores ' 
                .' WHERE id = '. $bat1id 
                ;
                
                //caters for the case when either batting or bowling is removed from the scorecard. we should remove the corresp record
                //else it will affect the stats ie averages
                
                //echo '<br> Heres the batting delete SQL: ' . $sql;
                $db->setQuery($sql);
                if (!$db->query())
                {
                    JError::raiseError( 500, $db->stderr() );
                    return false;
                }
            }
            else if ($firstinn_runsbatting != null) //TODO check if $firstinn_runsbatting is null? cos 0 is actually valid and so is ''
            {
                
                if($updating & $bat1id > 0)
                {
                    $sql = 'UPDATE #__statzone_battingscores ' 
                    .' SET runs = '. $firstinn_runsbatting .',' 
                    .' notout = ' . $firstinn_notout . ','
                    .' inningsno = 1 '                    
                    .' WHERE id = '. $bat1id 
                    //. ' WHERE scorecardid = '. $scorecardid 
                    //. ' AND playerid = '. $playerid
                    //. ' AND teamid = ' .$hometeamid
                    //. ' AND inningsno = 1 '
                    ;
                    
                    //echo '<br> Heres the batting update SQL: ' . $sql;
                    $db->setQuery($sql);
                    if (!$db->query())
                    {
                        JError::raiseError( 500, $db->stderr() );
                        return false;
                    }
                }
                else
                {
                    $sql = 'INSERT INTO #__statzone_battingscores (scorecardid,playerid,teamid,runs,notout,inningsno) VALUES (' . $scorecardid . ',' . $playerid. ', ' . $hometeamid. ','
                    . $firstinn_runsbatting . ','
                    . $firstinn_notout . ','
                    . '1'
                    . ')';
                    
                    //echo '<br> Heres the batting SQL: ' . $sql;
                    $db->setQuery($sql);
                    if (!$db->query())
                    {
                        JError::raiseError( 500, $db->stderr() );
                        return false;
                    }
                }
            }
            //2nd Innings
            if($bat2id > 0 & $secondinn_runsbatting == null)
            {
                //bat1id record exists in the existing scorecard but it has subsequently been removed
                $sql = 'DELETE FROM #__statzone_battingscores ' 
                .' WHERE id = '. $bat2id 
                ;
                
                //echo '<br> Heres the batting 2 delete SQL: ' . $sql;
                $db->setQuery($sql);
                if (!$db->query())
                {
                    JError::raiseError( 500, $db->stderr() );
                    return false;
                }
            }
            else if ($secondinn_runsbatting != null) //TODO check if $firstinn_runsbatting is null? cos 0 is actually valid
            {
                if($updating & $bat2id > 0)
                {
                    $sql = 'UPDATE #__statzone_battingscores ' 
                    .' SET runs = '. $secondinn_runsbatting .',' 
                    .' notout = ' . $secondinn_notout . ','
                    .' inningsno = 2 '                    
                    . ' WHERE id = '. $bat2id 
                    //. ' WHERE scorecardid = '. $scorecardid 
                    //. ' AND playerid = ' . $playerid
                    //. ' AND teamid = ' . $hometeamid
                    //. ' AND inningsno = 2 '
                    ;
                    
                    //echo '<br> Heres the batting 2 update SQL: ' . $sql;
                    $db->setQuery($sql);
                    if (!$db->query())
                    {
                        JError::raiseError( 500, $db->stderr() );
                        return false;
                    }
                }
                else
                {
                    $sql = 'INSERT INTO #__statzone_battingscores (scorecardid,playerid,teamid,runs,notout,inningsno) VALUES (' . $scorecardid . ',' . $playerid. ', ' . $hometeamid. ','
                    . $secondinn_runsbatting . ','
                    . $secondinn_notout . ','
                    . '2'
                    . ')';
                    
                    //echo '<br> Heres the batting SQL: ' . $sql;
                    $db->setQuery($sql);
                    if (!$db->query())
                    {
                        JError::raiseError( 500, $db->stderr() );
                        return false;
                    }
                }
            }
            
            // _____BOWLING______
            if($bowl1id > 0 & ($firstinn_O == null | $firstinn_O == ''))
            {
                //bowl1id record exists in the existing scorecard but it has subsequently been removed
                $sql = 'DELETE FROM #__statzone_bowlingscores ' 
                .' WHERE id = '. $bowl1id 
                ;
                
                //echo '<br> Heres the bowl1 delete SQL: ' . $sql;
                $db->setQuery($sql);
                if (!$db->query())
                {
                    JError::raiseError( 500, $db->stderr() );
                    return false;
                }
            }
            else if ($firstinn_O != null) //TODO check if $firstinn_O is null? cos 0 is actually valid
            {
                if($updating & $bowl1id > 0)
                {
                    $sql = 'UPDATE #__statzone_bowlingscores ' 
                    .' SET overs = '. $firstinn_O .',' 
                    .' maidens = ' . $firstinn_M . ','
                    .' runs = ' . $firstinn_R . ','
                    .' wickets = ' . $firstinn_W 
                    .' WHERE id = '. $bowl1id 
                    //. ' WHERE scorecardid = '. $scorecardid 
                    //. ' AND playerid = ' . $playerid
                    //. ' AND teamid = ' . $hometeamid
                    //. ' AND inningsno = 1 '
                    ;
                    
                    //echo '<br> Heres the bowling 1 update SQL: ' . $sql;
                    $db->setQuery($sql);
                    if (!$db->query())
                    {
                        JError::raiseError( 500, $db->stderr() );
                        return false;
                    }
                }
                else
                {
                    $sql = 'INSERT INTO #__statzone_bowlingscores (scorecardid,playerid,teamid,overs,maidens, runs, wickets,inningsno) VALUES (' . $scorecardid . ',' . $playerid. ', ' . $hometeamid. ','
                    . $firstinn_O . ','
                    . $firstinn_M . ','
                    . $firstinn_R . ','
                    . $firstinn_W . ','
                    . '1'
                    . ')';
                    
                    //echo '<br> Heres the bowling 1 SQL: ' . $sql;
                    $db->setQuery($sql);
                    if (!$db->query())
                    {
                        JError::raiseError( 500, $db->stderr() );
                        return false;
                    }
                }
            }
            
            if($bowl2id > 0 & $secondinn_O == null)
            {
                //bowl1id record exists in the existing scorecard but it has subsequently been removed
                $sql = 'DELETE FROM #__statzone_bowlingscores ' 
                .' WHERE id = '. $bowl2id 
                ;
                
                //echo '<br> Heres the bowl2 delete SQL: ' . $sql;
                $db->setQuery($sql);
                if (!$db->query())
                {
                    JError::raiseError( 500, $db->stderr() );
                    return false;
                }
            }
            else if ($secondinn_O != null) //TODO check if $firstinn_O is null? cos 0 is actually valid
            {
                if($updating & $bowl2id > 0)
                {
                    $sql = 'UPDATE #__statzone_bowlingscores ' 
                    .' SET overs = '. $secondinn_O .',' 
                    .' maidens = ' . $secondinn_M . ','
                    .' runs = ' . $secondinn_R . ','
                    .' wickets = ' . $secondinn_W 
                    .' WHERE id = '. $bowl2id 
                    //. ' WHERE scorecardid = '. $scorecardid 
                    //. ' AND playerid = ' . $playerid
                    //. ' AND teamid = ' . $hometeamid
                    //. ' AND inningsno = 2 '
                    ;
                    
                    //echo '<br> Heres the bowling 2 update SQL: ' . $sql;
                    $db->setQuery($sql);
                    if (!$db->query())
                    {
                        JError::raiseError( 500, $db->stderr() );
                        return false;
                    }
                }
                else
                {
                    $sql = 'INSERT INTO #__statzone_bowlingscores (scorecardid,playerid,teamid,overs,maidens, runs, wickets,inningsno) VALUES (' . $scorecardid . ',' . $playerid. ', ' . $hometeamid. ','
                    . $secondinn_O . ','
                    . $secondinn_M . ','
                    . $secondinn_R . ','
                    . $secondinn_W . ','
                    . '2'
                    . ')';
                    
                    //echo '<br> Heres the bowling 2 SQL: ' . $sql;
                    $db->setQuery($sql);
                    if (!$db->query())
                    {
                        JError::raiseError( 500, $db->stderr() );
                        return false;
                    }
                }
            }
        }
               
        switch ($task)
		{
			case 'apply':
				$link = 'index.php?option=com_statzone&c=scorecard&task=edit&cid[]='. $scorecardid ;
				break;

			case 'save':
			default:
				$link = 'index.php?option=com_statzone&c=scorecard';
				break;
		}

		$this->setRedirect( $link, JText::_( 'Scorecard ['.$scorecardid.'] Saved') );
        /**/
	}


	/**
	 * remove record(s)
	 * @return void
	 */
	function remove()
	{
        // Check for request forgeries
		JRequest::checkToken() or die( 'Invalid Token' );

		$this->setRedirect( 'index.php?option=com_statzone&c=scorecard' );

		// Initialize variables
		$db		=& JFactory::getDBO();
		$cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$n		= count( $cid );
		JArrayHelper::toInteger( $cid );

		if ($n)
		{
            $query = 'DELETE FROM #__statzone_battingscores'
			. ' WHERE scorecardid = ' . implode( ' OR id = ', $cid )
			;
			$db->setQuery( $query );
			if (!$db->query()) {
				JError::raiseWarning( 500, $db->stderr());
			}
            
            $query = 'DELETE FROM #__statzone_bowlingscores'
			. ' WHERE scorecardid = ' . implode( ' OR id = ', $cid )
			;
			$db->setQuery( $query );
			if (!$db->query()) {
				JError::raiseWarning( 500, $db->stderr());
			}
            
			$query = 'DELETE FROM #__statzone_scorecards'
			. ' WHERE id = ' . implode( ' OR id = ', $cid )
			;
			$db->setQuery( $query );
			if (!$db->query()) {
				JError::raiseWarning( 500, $db->stderr());
			}
		}

		$this->setMessage( JText::sprintf( 'Scorecard and stats removed', $n ) );
	}

    function publish()
	{
		// Check for request forgeries
		JRequest::checkToken() or die( 'Invalid Token' );

		$this->setRedirect( 'index.php?option=com_statzone&c=scorecard' );

		// Initialize variables
		$db			=& JFactory::getDBO();
		$user		=& JFactory::getUser();
		$cid		= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$task		= JRequest::getCmd( 'task' );
		$publish	= ($task == 'publish');
        $n			= count( $cid );

		if (empty( $cid )) {
			return JError::raiseWarning( 500, JText::_( 'No items selected' ) );
		}

		JArrayHelper::toInteger( $cid );
		$cids = implode( ',', $cid );

		$query = 'UPDATE #__statzone_scorecards'
		. ' SET published = ' . (int) $publish
		. ' WHERE id IN ( '. $cids.'  )'
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			return JError::raiseWarning( 500, $row->getError() );
		}
        
        $this->setMessage( JText::sprintf( $publish ? 'Scorecards published' : 'Scorecards unpublished', $n ) );
	}
    
	/**
	 * cancel editing a record
	 * @return void
	 */
	function cancel()
	{
		$msg = JText::_( 'Operation Cancelled' );
		$this->setRedirect( 'index.php?option=com_statzone&c=scorecard', $msg );
	}
    
    //Ajax function to build the player statz table given the home team selected
    //Validation will first occure to determine if the scorecard is not being duplicated.
    function buildteamstatslist()
    {
        $db			=& JFactory::getDBO();
		$user		=& JFactory::getUser();
        //ajax method to build the stats rows

        // get the data
        $data =& $this->get('Data');
    
        $scorecardid= JRequest::getCmd( 'id' ); //$post['id'];
        $hometeamid= JRequest::getCmd( 'hometeamidvalue' );//$post['hometeamid'];
        $oppteamid = JRequest::getCmd( 'oppteamid' );
        $firstinndate = JRequest::getCmd( 'firstinndate' );
        $duplicatescorecardfound = false;
        $duplicate_scid = -1;
        
         // import library
        jimport('joomla.utilities.simplexml');
        // create root node
        $xml = new JSimpleXMLElement('item', array('teamid' => $hometeamid));
        
        //Validate that the scorecard is not a duplicate
        // A duplicate scorecard is where the teams have played each other on 1st inn date
                
        //find if theres a duplicate scorecard 
        $sql = 'SELECT scorecard.id as id'
        .' FROM #__statzone_scorecards AS scorecard'
        .' WHERE teamidhome = ' . $hometeamid
        .' AND teamidopponent = ' .$oppteamid
        .' AND firstinndate = \''. $firstinndate . '\''
        ;
        $db->setQuery($sql);
        if (!$db->query())
        {
            $this->setRedirect( 'index.php?option=com_statzone' );
            $inputrows =& $xml->addChild('inputrows');
            //return JError::raiseWarning( 500, $db->getErrorMsg() );
            $inputrows->setData($db->getErrorMsg() );
        }
        $existingscorecardlist = $db->loadObjectList() ;
        foreach($existingscorecardlist as $sc)
        {
            $duplicate_scid = $sc->id;
            
        }
               
        //echo ' here we are in buildteamstatslist> scorecard id/ hometeamid = '.$scorecardid . ' > ' . $hometeamid . ' $post - hometeamidvalue='.$post['hometeamidvalue']; ;
        //for each potential player in that team, add a row
        if($duplicate_scid > 0)
        {
            //create the child node that will hold data
            $inputrows =& $xml->addChild('inputrows');
            
            //create a duplicatescorecardlink to let the user browse to the duplicate scorecard
            $duplicatescorecardlink		= JRoute::_( 'index.php?option=com_statzone&c=scorecard&task=edit&cid[]='. $duplicate_scid);
            $returnmsg = '<br><font color="red">'
                         .' <b>Duplicate score card</b>found. These teams ['.$hometeamid.','.$oppteamid.'] have played each other on ' .$firstinndate
                         .' <br>Follow link to edit duplicate score card: <a href=' . $duplicatescorecardlink . '>Duplicate scorecard</a>'
                         . '</font>'
                         ;
            $inputrows->setData($returnmsg);
        }
        else if($hometeamid > 0)
        {
            //get the list of players for that team
            $sql = 'SELECT player.id as playerid, player.firstname, player.surname '
            . 'FROM #__statzone_players as player '
            . 'INNER JOIN #__statzone_playerteams as map ON map.playerid = player.id '
            . 'WHERE map.teamid = ' . $hometeamid
            . ' ORDER BY player.surName'
            ;
            $db->setQuery($sql);
            if (!$db->query())
            {
                $this->setRedirect( 'index.php?option=com_statzone' );
                return JError::raiseWarning( 500, $db->getErrorMsg() );
            }
            $playerlist = $db->loadObjectList() ;
            $innings1row = '';
            //foreach of these players create a row, 
            foreach($playerlist as $playerrow)
            {
                $playerid = $playerrow->playerid;
                $playername = $playerrow->surname .', '.$playerrow->firstname;
                //get the rest of the stats
                
                //if this is an existing scorecard then show the results
                //else just show empty values
                $innings1row = $innings1row . ''
                    .'<tr>
                    <td nowrap=\'true\'>'.$playername .' ['.$playerid.']</td>
                    <td><input class="inputbox" type="text" name="firstinn_runsbatting_'.$playerid.'" id="firstinn_runsbatting_'.$playerid.'" size="10" value="" /></td>
                    <td><input class="inputbox" type="text" name="secondinn_runsbatting_'.$playerid.'" id="secondinn_runsbatting_'.$playerid.'" size="10" value="" /></td>
                    <td><input class="inputbox" type="text" name="firstinn_O_'.$playerid.'" id="firstinn_O_'.$playerid.'" size="10" value="" /></td>
                    <td><input class="inputbox" type="text" name="firstinn_M_'.$playerid.'" id="firstinn_M_'.$playerid.'" size="10" value="" /></td>
                    <td><input class="inputbox" type="text" name="firstinn_R_'.$playerid.'" id="firstinn_R_'.$playerid.'" size="10" value="" /></td>
                    <td><input class="inputbox" type="text" name="firstinn_W_'.$playerid.'" id="firstinn_W_'.$playerid.'" size="10" value="" /></td>
                    <td><input class="inputbox" type="text" name="secondinn_O_'.$playerid.'" id="secondinn_O_'.$playerid.'" size="10" value="" /></td>
                    <td><input class="inputbox" type="text" name="secondinn_M_'.$playerid.'" id="secondinn_M_'.$playerid.'" size="10" value="" /></td>
                    <td><input class="inputbox" type="text" name="secondinn_R_'.$playerid.'" id="secondinn_R_'.$playerid.'" size="10" value="" /></td>
                    <td><input class="inputbox" type="text" name="secondinn_W_'.$playerid.'" id="secondinn_W_'.$playerid.'" size="10" value="" /></td>
                    </tr>';
                    
                // add children
                //$playeridchild =& $xml->addChild('playerid');
                //$namechild =& $xml->addChild('playername');
                
                // set child data values
                //$playeridchild->setData($playerid);
                //$namechild->setData($playername);
                
            }
            $statstable = StatZoneControllerScorecard::getStatzTable($innings1row);
        
            //create the child node that will hold this data
            $inputrows =& $xml->addChild('inputrows');
            //echo $$innings1row;
            
            //add the data
            $inputrows->setData($statstable);
        }
        
        
                
        $document =& JFactory::getDocument();
        $document->setMimeEncoding('text/xml');
        
        echo '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
        echo $xml->toString();    
               
    }
    
    ///Ajax function that updates the dropdown sitting on the url with filter data applied to it
    function updatehometeamdropdown()
    {   
        $this->updateteamropdown("hometeamid");
        /*
        //get the name of the dropdown to filter
        //hometeamid
        
        //get the filter text
        //run the sql
        //format the response xml
        //echo the response
        $db			=& JFactory::getDBO();
		$user		=& JFactory::getUser();
        

        // get the data
        $data =& $this->get('Data');
    
        $hometeamidfilter= JRequest::getCmd( 'hometeamidfilter' );//$post['hometeamid'];
        $inputrows='';
        
         // import library
        jimport('joomla.utilities.simplexml');
        // create root node
        $xml = new JSimpleXMLElement('item', array('teamid' => $hometeamid));
        
                
        //find if theres a duplicate scorecard 
        $sql = 'SELECT t.id as teamid, t.name AS teamname'
		. ' FROM #__statzone_teams AS t'
		. ' INNER JOIN #__statzone_clubs AS c ON c.id = t.clubid'
		. ' INNER JOIN #__statzone_province AS provinces ON c.provinceid = provinces.id'
        ;
        
        if($hometeamidfilter > '')
        {
            $sql .= ' WHERE t.name like \'%'.$hometeamidfilter.'%\'';
        }
        
        $sql .= ' ORDER BY t.name';
        //echo $sql;
        $db->setQuery($sql);
        if (!$db->query())
        {
            $this->setRedirect( 'index.php?option=com_statzone' );
            $inputrows =& $xml->addChild('inputrows');
            //return JError::raiseWarning( 500, $db->getErrorMsg() );
            $inputrows->setData($db->getErrorMsg() );
            
            $document =& JFactory::getDocument();
            $document->setMimeEncoding('text/xml');
            
            echo '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
            echo $xml->toString();  
            return;
        }
        $teamlist = $db->loadObjectList() ;
        //create the child node that will hold data
        $inputrows =& $xml->addChild('inputrows');
        $output = '<select id="hometeamid" class="inputbox" onchange="buildresultlist();" size="1" name="hometeamid">';
        
        foreach($teamlist as $team)
        {
            $teamid = $team->teamid;
            $teamname = $team->teamname;
            //$option =& $xml->addChild('option');
            
            $output .= $this->new_option($teamname, $teamid);
            
            //$returnmsg .= '<option value="'.$teamid.'">'.$teamname.'</option>';
            
            //$returnmsg = $teamid.','.$teamname;
            //$option->setData($returnmsg);
        }
        $inputrows->setData($output);
        
        $document =& JFactory::getDocument();
        $document->setMimeEncoding('text/xml');
        
        echo '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
        echo $xml->toString();  */
    }
    
    ///Ajax function that updates the dropdown sitting on the url with filter data applied to it
    function updateteamropdown($controlid)
    {
        //get the name of the dropdown to filter
        //hometeamid
        
        //get the filter text
        //run the sql
        //format the response xml
        //echo the response
        $db			=& JFactory::getDBO();
		$user		=& JFactory::getUser();
        

        // get the data
        $data =& $this->get('Data');
    
        $hometeamidfilter= JRequest::getCmd( $controlid. 'filter' );//$post['hometeamid'];
        $inputrows='';
        
         // import library
        jimport('joomla.utilities.simplexml');
        // create root node
        $xml = new JSimpleXMLElement('item', array('teamid' => $hometeamid));
        
                
        //find if theres a duplicate scorecard 
        $sql = 'SELECT t.id as teamid, t.name AS teamname'
		. ' FROM #__statzone_teams AS t'
		. ' INNER JOIN #__statzone_clubs AS c ON c.id = t.clubid'
		. ' INNER JOIN #__statzone_province AS provinces ON c.provinceid = provinces.id'
        ;
        
        if($hometeamidfilter > '')
        {
            $sql .= ' WHERE t.name like \'%'.$hometeamidfilter.'%\'';
        }
        
        $sql .= ' ORDER BY t.name';
        //echo $sql;
        $db->setQuery($sql);
        if (!$db->query())
        {
            $this->setRedirect( 'index.php?option=com_statzone' );
            $inputrows =& $xml->addChild('inputrows');
            //return JError::raiseWarning( 500, $db->getErrorMsg() );
            $inputrows->setData($db->getErrorMsg() );
            
            $document =& JFactory::getDocument();
            $document->setMimeEncoding('text/xml');
            
            echo '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
            echo $xml->toString();  
            return;
        }
        $teamlist = $db->loadObjectList() ;
        //create the child node that will hold data
        $inputrows =& $xml->addChild('inputrows');
        $output = '<select id="'.$controlid.'" class="inputbox" onchange="buildresultlist();" size="1" name="'.$controlid.'">';
        
        foreach($teamlist as $team)
        {
            $teamid = $team->teamid;
            $teamname = $team->teamname;
            //$option =& $xml->addChild('option');
            
            $output .= $this->new_option($teamname, $teamid);
            
            //$returnmsg .= '<option value="'.$teamid.'">'.$teamname.'</option>';
            
            //$returnmsg = $teamid.','.$teamname;
            //$option->setData($returnmsg);
        }
        $inputrows->setData($output);
        
        $document =& JFactory::getDocument();
        $document->setMimeEncoding('text/xml');
        
        echo '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
        echo $xml->toString();  
    }
    
    function updateoppteamiddropdown()
    {
        $this->updateteamropdown("oppteamid");
    }
    
    function new_option(&$text, &$value)
    {
        $output = "<option value=\"" . $value . "\"";

        //if ($value === $value_cmp) 
        //{
        //    $output .= " selected";
        //}

        $output .= ">" . $text . "</option>";

        return ($output);
    }
}
?>
